<?php

declare(strict_types=1);

namespace App\Common\Service;

use App\Activity\Model\ActivityModel;
use App\Common\Constants\ErrorCode;
use App\Common\Model\SystemLogModel;
use App\Common\Model\SystemOperationLogModel;
use App\Resource\Event\UpdateGoodsCache;
use App\Resource\Model\CategoryModel;
use App\Resource\Model\CookbookModel;
use App\Resource\Model\CrdCategoryModel;
use App\Resource\Model\CrdNavigationModel;
use App\Resource\Model\GoodsModel;
use App\Resource\Model\GroundPromotionUserModel;
use App\Resource\Model\MenuModel;
use App\Resource\Model\NavigationModel;
use App\Resource\Model\RegionModel;
use App\Resource\Model\ShopGroupModel;
use App\Resource\Model\ShopModel;
use App\Resource\Model\SystemModel;
use App\Resource\Service\Goods\GoodsBaseService;
use App\User\Model\UserModel;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use Phper666\JWTAuth\JWT;
use Exception;
use Psr\EventDispatcher\EventDispatcherInterface;
use League\Flysystem\Filesystem;

class BaseService
{

    /**
     * @Inject
     * @var JWT
     */
    protected $jwt;

    protected $redis;

    protected $groupRedis;

    protected $seckillRedis;

    public $userRedis;

    public $resourceRedis;

    public $smsRedis;

    public $buildRedis;

    /**
     * @Inject
     *
     * @var RequestInterface
     */
    protected $request;

    protected $container;

    /**
     * @Inject
     * @var Arr
     */
    protected $arr;


    /**
     * http Client
     * @var
     */
    protected $httpClient;

    /**
     * @var
     */
    private $clientFactory;

    protected $eventDispatcher;

    protected $orderDriver;

    protected $driverLog;
    /**
     * @Inject()
     * @var Filesystem
     */
    protected $filesystem;

    /**
     * BaseService constructor.
     */
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->container = $container;
        $this->redis = $container->get(RedisFactory::class)->get('default');
        $this->groupRedis = $container->get(RedisFactory::class)->get('group');
        $this->seckillRedis = $container->get(RedisFactory::class)->get('seckill');
        $this->userRedis = $container->get(RedisFactory::class)->get('user');
        $this->resourceRedis = $container->get(RedisFactory::class)->get('resource');
        $this->smsRedis = $container->get(RedisFactory::class)->get('sms');
        $this->buildRedis = $container->get(RedisFactory::class)->get('build');
        $this->clientFactory = $container->get(ClientFactory::class);
        $this->eventDispatcher = $container->get(EventDispatcherInterface::class);
        $this->orderDriver = $container->get(DriverFactory::class)->get('order');
        $this->driverLog = $container->get(DriverFactory::class)->get('log');
        $this->httpClient = $this->clientFactory->create(['timeout' => 50,'verify' => false,'headers' => ['Content-Type' => 'application/json']]);
    }

    /**
     * 根据token解析获取用户信息
     * @return array|Builder|Model|object
     * @author zhangzhiyuan
     * mailbox 466180170@qq.com
     */
    public function getCurrentInfo()
    {
        $currentUserInfo ='';
        try {
            $jwtData = $this->jwt->getParserData();
            switch ($jwtData['jwt_scene']){
                case 'default':
                    $uid = $jwtData['uid'];
                    $currentUserInfo = UserModel::query()->where('id', $uid)->first();
                    $currentUserInfo->permission = $currentUserInfo->getMenu();
                    break;
                case 'shopApp':
                    $currentUserInfo = $jwtData;
                    break;
                case 'miniProgram':
                    $currentUserInfo = $jwtData['mid'];
                    break;
            }
            return $currentUserInfo;
        } catch (Exception $e) {
            return $currentUserInfo;
        }
    }
    /**
     * @param string $category  场景标识
     * @param int $id
     * @param string $type      类别
     * @param null $shopType    1 为次日达，其他场景不传值
     *
     * @return array
     */
    public function editStatus(string $category, int $id, string $type = null, $shopType = null)
    {
        $where = [];
        $confirmStatus = null;
        switch ($category) {
            case 'user':
                $db = UserModel::query();
                $key = 'id';
                if (!empty($type)) {
                    $where['role'] = $type;
                }
                break;
            case 'category':
                if($shopType){
                    $db = CrdCategoryModel::query();
                }else{
                    $db = CategoryModel::query();
                }
                $key = 'id';
                break;
            case 'navigation':
                if($shopType){
                    $db = CrdNavigationModel::query();
                }else{
                    $db = NavigationModel::query();
                }
                $key = 'id';
                if (!empty($type)) {
                    $where['type'] = $type;
                }
                break;
            case 'activity':
                $db = ActivityModel::query();
                $key = 'activityID';
                break;
            case 'shop':
                $db = ShopModel::query();
                $key = 'shop_id';
                if(isset($type) && $type != '') $confirmStatus = $type;
                break;
            case 'menu':
                $db = MenuModel::query();
                $key = 'id';
                break;
            case 'goods':
                $db = GoodsModel::query();
                $key = 'id';
                break;
            case 'cookbook':
                $db = CookbookModel::query();
                $key = 'id';
                break;
            case 'ground':
                $db = GroundPromotionUserModel::query();
                $key = 'id';
                break;
        }
        $where[$key] = $id;
        $dbInfo = $db->where($where)->first();
        if(isset($confirmStatus) && $confirmStatus != ''){
            $dbInfo->status = $statusValue = $confirmStatus;
        }else{
            if ($dbInfo->status == 1) {
                $dbInfo->status = $statusValue = 0;
            } else {
                $dbInfo->status = $statusValue = 1;
            }
        }
        $res = $dbInfo->save();
        if ($res) {
            // 更新缓存操作
            if ($category == 'goods') {
                $this->redis->hSet('Goods:' . $id, 'status', $statusValue);
                $this->eventDispatcher->dispatch(new UpdateGoodsCache('is_sale', $id, $dbInfo));
            }
            if($category == 'shop'){
                // 删除附近店铺的 Redis
                $keys = $this -> resourceRedis -> keys('nearShop*');
                $this -> resourceRedis -> del($keys);
            }
            if ($category == 'activity') {
                // 团购活动存入redis
//                $dbInfo = $db->where($where)->select(['activityType','begin_date','end_date', 'activity_prams'])->first();
                //0 禁用 1启用
                if ($statusValue == 0 && $dbInfo->activityType == 0) {
                    $this->groupRedis->hDel('group:timer', (string)$id);
                }
                if ($statusValue == 1 && $dbInfo->activityType == 0) {
                    $join = [
                        'acId' => $id,
                        'begin' => strtotime($dbInfo->begin_date),
                        'end' => strtotime($dbInfo->end_date),
                        'need' => json_decode($dbInfo->activity_prams, true)['group_num']
                    ];
                    $this->groupRedis->hSet('group:timer', (string)$id, json_encode($join));
                }
            }
            switch ($statusValue){
                case 0:
                    $operationResults = '禁用';
                    break;
                case 1:
                    $operationResults = '启用';
                    break;
                case 2:
                    $operationResults = '歇业';
                    break;
            }
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id, 'operation_results' => $operationResults]];
//            return ['code' => ErrorCode::SUCCESS, 'data' => $res];
        }

        return ['code' => ErrorCode::NOT_IN_FORCE];
    }


    /**
     * @param int|null $day
     * @return array
     */
    public function getDateRangeByDayNum(int $day = null)
    {
        if ($day) {
            $now = time();
            $end = date('Y-m-d H:i:s', $now);
            $start = date('Y-m-d H:i:s', strtotime("-$day day", $now));
            return ['start' => $start, 'end' => $end];
        }
    }

    /**
     * 两个日期之间的天数
     * @param string $date_s
     * @param string $date_e
     * @return float|int
     */
    public function diffBetweenTwoDays(string $date_s, string $date_e)
    {
        $second1 = strtotime($date_s);
        $second2 = strtotime($date_e);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        $day = (($second1 - $second2) / 86400);
        return $day;
    }

    /**
     * @param string $date_s
     * @param string $date_e
     * @return float|int|mixed|string
     */
    public function diffBetweenMonthNum(string $date_s, string $date_e)
    {
        $date1_stamp = strtotime($date_s);
        $date2_stamp = strtotime($date_e);
        list($date_1['y'], $date_1['m']) = explode("-", date('Y-m', $date1_stamp));
        list($date_2['y'], $date_2['m']) = explode("-", date('Y-m', $date2_stamp));
        return abs($date_1['y'] - $date_2['y']) * 12 + $date_2['m'] - $date_1['m'];
    }

    /**
     * 两个时间间的所有时间
     * @param string $start
     * @param string $end
     * @return array
     */
    public function prTime(string $start, string $end)
    {
        $dt_start = strtotime($start);
        $dt_end = strtotime($end);
        $arr = [];
        while ($dt_start <= $dt_end) {
            array_push($arr, date('Y-m-d H', $dt_start));
            $dt_start = strtotime('+1 hour', $dt_start);
        }
        return $arr;
    }

    /**
     * 两个日期间所有日期
     * @param string $start
     * @param string $end
     * @return array
     */
    public function prDates(string $start, string $end)
    {
        $dt_start = strtotime($start);
        $dt_end = strtotime($end);
        $arr = [];
        while ($dt_start <= $dt_end) {
            //echo date('Y-m-d',$dt_start)."\n";
            array_push($arr, date('Y-m-d', $dt_start));
            $dt_start = strtotime('+1 day', $dt_start);
        }
        return $arr;
    }

    /**
     * 两个月份间所有月份
     * @param string $start
     * @param string $end
     * @return array
     */
    public function prMonths(string $start, string $end)
    {
        $dt_start = strtotime($start);
        $dt_end = strtotime($end);
        $arr = [];
        while ($dt_start <= $dt_end) {
            //echo date('Y-m-d',$dt_start)."\n";
            array_push($arr, date('Y-m', $dt_start));
            $dt_start = strtotime('+1 month', $dt_start);
        }
        return $arr;
    }

    /**
     * 求两个数的比和趋势↑/↓/-
     * @param string $basicCount
     * @param string $contrastCount
     * @return array
     */
    public function coefficientsAndTrends(string $basicCount, string $contrastCount)
    {
        if ($contrastCount > 0) {
            $ratio = bcdiv((string)$basicCount, (string)$contrastCount, 2);
            if ($ratio > 0) {
                $changeFlag = 1;
            } else {
                $changeFlag = -1;
            }
            if ($ratio * 100 == 0) {
                $ratio = '100%';
            } else {
                $ratio = ($ratio * 100) . '%';
            }
        } else {
            $changeFlag = 0;
            $ratio = '--';
        }
        return ['changeFlag' => $changeFlag, 'ratio' => $ratio];
    }

    /**
     * @param string $age (15-23)
     * @return array
     */
    public function getDateRangeByAge(string $age = null)
    {
        if ($age) {
            $min = explode('-', $age)[0];
            $max = explode('-', $age)[1];
            $min_age = date('Y', strtotime("-$max year", time()));
            $max_age = date('Y', strtotime("-$min year", time()));
            return ['min' => $min_age, 'max' => $max_age];
        }
    }

    /**
     * 根据店群 ID 查询店群名称
     * @param int $shop_group_id
     * @return mixed
     */
    public function getGroupNameByGroupId(int $shop_group_id)
    {
        return ShopGroupModel::where('id', $shop_group_id)->value('shop_group_name');
    }

    /**
     * 根据分类 ID 查询分类名称
     * @param int $cate_td
     * @return mixed
     */
    public function getCateNameByCateId(int $cate_td)
    {
        return CategoryModel::where('id', $cate_td)->value('title');
    }

    /**
     * 获取省市区和详细地址全称
     * @param int $province
     * @param int $city
     * @param int $country
     * @param string $address
     * @return string
     */
    public function getAddress(int $province, int $city, int $country, string $address)
    {
        $list = RegionModel::whereIn('region_id', [$province, $city, $country])->select(['region_name'])->get()->toArray();
        $province = $list[0]['region_name'];
        $city = $list[1]['region_name'];
        $country = $list[2]['region_name'];

        return $province . $city . $country . $address;
    }



    /**
     * 生成唯一编码
     * @param int $length
     * @return string
     */
    public function uniqidNumberCode(int $length = 10)
    {
        $time = time() . '';
        if ($length < 10) {
            $length = 10;
        }
        $string = ($time[0] + $time[1]) . substr($time, 2) . rand(0, 9);
        while (strlen($string) < $length) {
            $string .= rand(0, 9);
        }
        return $string;
    }

    /**
     * @return bool
     */
    public function isDevelopment()
    {
        if (config('app_env') === 'dev') {
            return true;
        }
        return false;
    }

    /**
     * @param bool $param
     * @param string $path
     */
    public function prf(bool $param, string $path = 'debug/')
    {
        $style = is_bool($param) ? 1 : 0;
        if ($style) {
            $outStr = "\r\n";
            $outStr .= '<------------------------------------------------------------------------';
            $outStr .= "\r\n";
            $outStr .= date('Y-m-d H:i:s', time());
            $outStr .= "\r\n";
            $outStr .= $param == TRUE ? 'bool:TRUE' : 'bool:FALSE';
            $outStr .= "\r\n";
            $outStr .= '------------------------------------------------------------------------>';
            $outStr .= "\r\n";
        } else {
            $outStr = "\r\n";
            $outStr .= '<------------------------------------------------------------------------';
            $outStr .= "\r\n";
            $outStr .= date('Y-m-d H:i:s', time());
            $outStr .= "\r\n";
            $outStr .= print_r($param, 1);
            $outStr .= "\r\n";
            $outStr .= '------------------------------------------------------------------------>';
            $outStr .= "\r\n";
        }
        $backTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        unset($backTrace[0]['args']);
        $outStr .= print_r($backTrace[0], 1);
        $outStr .= "\r\n";
        $path .= date('Y-m-d', time());
        file_put_contents($path . '-log.txt', $outStr, FILE_APPEND);
    }

    /**
     * @param int $id
     * @param string $type
     * @return array
     */
    public function editHotOrHome(int $id, string $type)
    {
        switch ($type) {
            case 'is_home':
                $field = 'is_home';
                $typeStr = '首页';
                break;
            case 'is_hot':
                $field = 'hot_id';
                $typeStr = '热销';
                break;
        }
        $goods = GoodsModel::query()->where(['id' => $id])->first();
        if ($goods->{$field} == 1) {
            $goods->{$field} = 0;
            //首页不展示
            $this->redis->Lpush('Home:Hot', $id);
            $valueStr = '关闭';
        } else {
            $goods->{$field} = 1;
            //首页展示
            $this->redis->Lpush('Home:Hot', $id);
            $valueStr = '开启';
        }
        $res = $goods->save();
        if ($res) {
            $this->eventDispatcher->dispatch(new UpdateGoodsCache($type, $id, $goods));
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id, 'operation_results' => $typeStr.$valueStr]];

        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * 根据上下级关系生成树状结构数组
     * @param array $array
     * @param string $field
     * @return array
     */
    public function generateTree(array $array, string $field = 'pid')
    {
        //第一步 构造数据
        $items = array();
        foreach ($array as $value) {
            $items[$value['id']] = $value;
        }
        //第二部 遍历数据 生成树状结构
        $tree = array();
        foreach ($items as $key => $value) {
            if (isset($items[$value[$field]])) {
                $items[$value[$field]]['children'][] = &$items[$key];
            } else {
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }

    /**
     * 写入系统日志
     * @param string $action
     * @param string $content
     */
    public function write(string $action, string $content)
    {
        if (isset($this->request->pathInfo)) {
            $node = $this->request->path();
            $ip = $this->request->server('remote_addr');
        }
        $data = [
            'node' => $node??'',
            'action' => $action,
            'content' => $content,
            'geoip' => $ip??'',
            'username' => '',
            'create_at' => date('Y-m-d H:i:s')
        ];
        SystemLogModel::query()->create($data);
    }

    /**
     * 写入系统日志
     * @param string $action
     * @param string $content
     */
    public function writeLogs($node,string $action, string $content)
    {
        $data = [
            'node' => $node,
            'action' => $action,
            'content' => $content,
            'geoip' =>'',
            'username' => '',
            'create_at' => date('Y-m-d H:i:s')
        ];
        SystemLogModel::query()->create($data);
    }

    /**
     * @param string $meter
     * @return string
     */
    public function m2Km(string $meter){
        if($meter > 1000){
            $s = round($meter/1000,2);
            return $s."公里";
        }else{
            return round($meter)."米";
        }
    }


    /**
     * http get
     * @param $url
     * @param null $data
     * @return string
     */
    public function https_request(string $url, $data = null)
    {
        $httpResponse = $this->httpClient->get($url);
        return $httpResponse->getBody()->getContents();
    }

    /**
     * http post
     * @param string $url
     * @param string $param
     * @return string
     */
    public function do_request_post($url = '', $param = '')
    {

        $headers = [
            "Content-Type: application/json",
            "Content-Length: " . strlen($param) . "",
            "Accept: application/json",
        ];
        $options = [
            'headers' => $headers,
            'body' => $param
        ];
        $httpResponse = $this->httpClient->post($url, $options);
        return $httpResponse->getBody()->getContents();
    }

    /**
     * http post form_params
     * @param $url
     * @param $post_data
     * @return string
     */
    public function http_post_json($url, $post_data)
    {
        $headers = [
            'Content-Type: application/x-www-form-urlencoded',
        ];
        $options = [
            'headers' => $headers,
            'form_params' => $post_data
        ];
        $httpResponse = $this->httpClient->post($url, $options);
        return $httpResponse->getBody()->getContents();
    }

    /**
     * 小程序 access_token
     * @return mixed
     */
    protected function getMiniAppToken(){
        $appid     = config("wechat.app_id");
        $appSecret = config("wechat.secret");
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appSecret;
        $res = $this->https_request($url);
        return json_decode($res, true)['access_token'];
    }

    /**
     * 小程序模板消息
     * @param string $openid
     * @param string $template_id
     * @param string $page
     * @param array $map
     * @return mixed
     */
    protected function sendMiniAppSubscribeMsg(string $openid, string $template_id, string $page, array $map){
        $miniAppToken = $this->getMiniAppToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $miniAppToken;
        $data['touser'] = $openid;
        $data['template_id'] = $template_id;
        $data['page'] = $page;
        $data['data'] = $map;
        $res = $this->do_request_post($url, json_encode($data));
        return ['prams'=>$data,'response'=>json_decode($res, true)];
    }
    /**
     * 查看指定 Key 的 Redis 数据是否存在
     * @param string $type
     * @param string $key
     * @return mixed
     */
    public function isRedisExist(string $type, string $key)
    {
        return $this->$type->exists($key);
    }

    /**
     * 删除 Redis
     * @param string $type
     * @param string $key
     */
    public function delRedisData(string $type, string $key)
    {
        $this -> $type -> del($key);
        return true;
    }

    /**
     * 格式化返回参数
     *
     * @param array $data
     * @param int $total
     * @return array
     */
    public function success($data = [], $total = 0)
    {
        return [
            'total' => $total,
            'data'  => $data,
            'code'  => ErrorCode::SUCCESS,
        ];
    }

    /**
     * 错误格式
     *
     * @param $code
     * @param string $msg
     * @return array
     */
    public function error($code, $msg = '')
    {
        !$msg && $msg = ErrorCode::getMessage($code);
        return [
            'msg'  => $msg,
            'code' => $code,
        ];
    }

    /**
     * 批量更新
     *
     * Author: mengchenchen
     * Created_at: 2021/1/6 0006 14:26
     * Updated_at: 2021/1/6 0006 15:43
     *
     * @param $tableName [表名]
     * @param array $multipleData [批量数据，第一个 key 为 where 条件]
     * @return false|int
     */
    public function updateBatch($tableName, $multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new Exception("数据不能为空");
            }
            $firstRow = current($multipleData);

            $updateColumn = array_keys($firstRow);
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            return DB::update($updateSql, $bindings);
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 获取次日达自提日期（功能适用平台多端）业务场景（次日达商品展示）
     * @return false|string
     * @author zhangzhiyuan
     */
    public function getOverNightTakeDate()
    {
        $deadline = SystemModel::query()->where('name', 'cut_off_time')->value('value');
        !$deadline && $deadline = '22:00';
        $takeDate = date('m/d', strtotime('+1 day'));
        if (date('H:i') > $deadline) {
            $takeDate = date('m/d', strtotime('+2 day'));
        }
        return $takeDate;
    }


    /**
     * 及时达商品档案价格库存信息转换公共服务
     * @param array $GoodsArchivesCollect
     * @param array $schemePriceArr 价格集合
     * @param $lsyShopNo
     * @return array
     * @author ran
     * @date 2021-02-25 14:34
     * mailbox 466180170@qq.com
     *价格计算规则 读取龙收银非标品为公斤单价需转换斤的单价 即 （公斤价/1000)*平台转换系数（备注:系数以斤为单位） 如果读取不到POS价格默认平台价格
     *POS库存计算规则 read_pos_stock=1的情况 读取龙收银标品非标品 (（POS库存*1000）/ratio=平台可售卖库存)-安全库存  标品 读取龙收银库存小数情况向下取整  读取不到默认0
     */
    protected function getCommonChangeGoodsPriceOrStock(array $GoodsArchivesCollect,array $schemePriceArr,$lsyShopNo): array
    {
        $redisStock = $this->buildRedis->hGetAll("lsy:{$lsyShopNo}:stock");//龙收银库存
        foreach($GoodsArchivesCollect as $key=>$goods){
            $surplusQuantity = isset($redisStock[$goods['goods_crm_code']]) ? $redisStock[$goods['goods_crm_code']]:0;
            if ($goods['read_pos_stock'] == GoodsBaseService::GOODS_READ_POS_STOCK_1){
                // 读pos库存 变为份
                if ($goods['scant_id'] == GoodsBaseService::GOODS_SCANT_1){
                    $pos_goods_stock = $goods['ratio'] == 0 ? 0:bcdiv(bcmul((string)$surplusQuantity, '1000'), (string)$goods['ratio']);
                }else{
                    $pos_goods_stock = (string)floor($surplusQuantity);
                }
                // 可售卖库存
                $can_buy_stock = bcsub($pos_goods_stock, (string)$goods['safety_stock']);
                $goods['surplusQuantity'] = $can_buy_stock <= 0 ? -1:$can_buy_stock;
            }else{
                // 系数为0 造成排序错乱
                $goods['surplusQuantity'] = (string)$goods['number_stock'];
            }
            if ($goods['read_pos_price'] == GoodsBaseService::GOODS_READ_POS_PRICE_1){
                if (array_key_exists($goods['goods_crm_code'], $schemePriceArr)){
                    $posSellingPrice = $schemePriceArr[$goods['goods_crm_code']]['price']??$goods['price_selling'];
                    $posMarketPrice = $schemePriceArr[$goods['goods_crm_code']]['stdPrice']??$goods['price_market'];
                }else{
                    $posSellingPrice =$goods['price_selling'];
                    $posMarketPrice = $goods['price_market'];
                }
                // 读pos价格
                if ($goods['scant_id'] == GoodsBaseService::GOODS_SCANT_1) {
                    // 非标品
                    $goods['price_selling'] = bcmul(bcdiv($posSellingPrice,'1000',6),(string)$goods['ratio'],2);
                    $goods['price_market'] = bcmul(bcdiv($posMarketPrice,'1000',6),(string)$goods['ratio'],2);
                } else {
                    // 标品
                    $goods['price_selling'] = $posSellingPrice;
                    $goods['price_market'] = $posMarketPrice;
                }
            }
            $GoodsArchivesCollect[$key]['price_selling']=$goods['price_selling'];
            $GoodsArchivesCollect[$key]['price_market']=$goods['price_market'];
            $GoodsArchivesCollect[$key]['number_stock']=(int)$goods['surplusQuantity'];
        }
        return $GoodsArchivesCollect;
    }

    /**
     * @param $info
     * @return array
     * @author ran
     * @date 2021-03-02 10:21
     * mailbox 466180170@qq.com
     */

    public function changeStatusLog($info)
    {
        try {
            SystemOperationLogModel::create([
                'uid' => $info['uid'] ?? '',
                'ip' => $info['ip'] ?? '',
                'operation_describe' => $info['operation_describe'] ?? '',
                'target_id' => $info['target_id'] ?? '',
                'class_name' => $info['class_name'] ?? '',
                'method_name' => $info['method_name'] ?? '',
                'remarks' => $info['remarks'] ?? '',
                'request_param' => $info['request_param'] ?? ''
            ]);
        } catch (Exception $e) {
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => []];
    }

    /**
     * 解析一个链接中的参数，以数组形式展现
     * @param $query
     * @return array
     */
    public function convertUrlQuery($query): array
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
}
